<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'

// ... 保持之前的基础配置 ...

// 游戏模式
const gameMode = ref('single') // 'single' 或 'battle'
const difficulty = ref('normal') // 'easy', 'normal', 'hard'
const selectedSkin = ref('default')

// 排行榜
const leaderboard = ref([])
const playerName = ref('')

// 多人对战
const players = ref([
  { id: 1, name: '玩家1', snake: null, score: 0, alive: true },
  { id: 2, name: 'AI玩家', snake: null, score: 0, alive: true }
])

// 特殊技能
const skills = {
  speedBoost: {
    name: '加速冲刺',
    icon: '⚡',
    duration: 3000,
    cooldown: 10000,
    active: false,
    lastUsed: 0
  },
  shield: {
    name: '护盾',
    icon: '🛡️',
    duration: 5000,
    cooldown: 15000,
    active: false,
    lastUsed: 0
  },
  magnet: {
    name: '磁力',
    icon: '🧲',
    duration: 4000,
    cooldown: 12000,
    active: false,
    lastUsed: 0
  }
}

// 皮肤系统
const skins = {
  default: {
    name: '经典',
    colors: ['#4CAF50', '#45a049'],
    pattern: 'gradient'
  },
  rainbow: {
    name: '彩虹',
    colors: ['#FF0000', '#FF7F00', '#FFFF00', '#00FF00', '#0000FF', '#4B0082', '#9400D3'],
    pattern: 'segments'
  },
  galaxy: {
    name: '星空',
    colors: ['#000033', '#4444aa'],
    pattern: 'sparkle'
  },
  fire: {
    name: '火焰',
    colors: ['#FF4500', '#FF8C00'],
    pattern: 'flame'
  }
}

// 音效系统
const sounds = {
  eat: new Audio('/sounds/eat.mp3'),
  collision: new Audio('/sounds/collision.mp3'),
  skill: new Audio('/sounds/skill.mp3'),
  background: new Audio('/sounds/background.mp3')
}

// 静音控制
const isMuted = ref(false)

// 使用技能
const useSkill = (skillName) => {
  const skill = skills[skillName]
  const now = Date.now()
  
  if (now - skill.lastUsed < skill.cooldown) return
  
  skill.active = true
  skill.lastUsed = now
  
  if (!isMuted.value) sounds.skill.play()
  
  switch (skillName) {
    case 'speedBoost':
      snake.value.speed *= 2
      setTimeout(() => {
        snake.value.speed /= 2
        skill.active = false
      }, skill.duration)
      break
      
    case 'shield':
      snake.value.isInvincible = true
      setTimeout(() => {
        snake.value.isInvincible = false
        skill.active = false
      }, skill.duration)
      break
      
    case 'magnet':
      // 吸引附近的食物
      const magnetRange = 5
      foods.value.forEach(food => {
        const head = snake.value.body[0]
        const dx = head.x - food.x
        const dy = head.y - food.y
        const distance = Math.sqrt(dx * dx + dy * dy)
        
        if (distance < magnetRange) {
          food.x += Math.sign(dx) * 0.5
          food.y += Math.sign(dy) * 0.5
        }
      })
      setTimeout(() => {
        skill.active = false
      }, skill.duration)
      break
  }
}

// AI控制
const updateAI = () => {
  if (gameMode.value !== 'battle') return
  
  const aiSnake = players.value[1].snake
  if (!aiSnake || !aiSnake.body.length) return
  
  const head = aiSnake.body[0]
  const nearestFood = foods.value.reduce((nearest, food) => {
    const distance = Math.sqrt(
      Math.pow(head.x - food.x, 2) + 
      Math.pow(head.y - food.y, 2)
    )
    return !nearest || distance < nearest.distance 
      ? { food, distance }
      : nearest
  }, null)
  
  if (nearestFood) {
    const dx = nearestFood.food.x - head.x
    const dy = nearestFood.food.y - head.y
    
    aiSnake.direction = {
      x: Math.sign(dx),
      y: Math.sign(dy)
    }
  }
}

// 更新游戏状态
const update = () => {
  if (gameOver.value) return
  
  // 更新所有玩家
  players.value.forEach(player => {
    if (!player.snake || !player.alive) return
    
    const head = { ...player.snake.body[0] }
    head.x += Math.round(player.snake.direction.x)
    head.y += Math.round(player.snake.direction.y)
    
    player.snake.body.unshift(head)
    
    // 检查食物碰撞
    const foodIndex = foods.value.findIndex(food => 
      food.x === head.x && food.y === head.y
    )
    
    if (foodIndex !== -1) {
      const food = foods.value[foodIndex]
      player.score += food.type.points
      foods.value.splice(foodIndex, 1)
      generateFood()
      
      if (!isMuted.value) sounds.eat.play()
    } else {
      player.snake.body.pop()
    }
    
    // 检查碰撞
    if (!player.snake.isInvincible && checkCollision(player.snake)) {
      player.alive = false
      if (!isMuted.value) sounds.collision.play()
      
      // 检查游戏是否结束
      const alivePlayers = players.value.filter(p => p.alive)
      if (alivePlayers.length <= 1) {
        gameOver.value = true
        updateLeaderboard()
      }
    }
  })
  
  updateAI()
}

// 更新排行榜
const updateLeaderboard = () => {
  const entry = {
    name: playerName.value || '匿名玩家',
    score: score.value,
    date: new Date().toLocaleDateString()
  }
  
  leaderboard.value.push(entry)
  leaderboard.value.sort((a, b) => b.score - a.score)
  leaderboard.value = leaderboard.value.slice(0, 10)
  
  // 保存到本地存储
  localStorage.setItem('snakeLeaderboard', JSON.stringify(leaderboard.value))
}

// 渲染游戏
const render = () => {
  if (!ctx.value) return
  
  // ... 保持之前的基础渲染逻辑 ...
  
  // 渲染技能状态
  Object.entries(skills).forEach(([name, skill], index) => {
    const x = GAME_WIDTH - 150
    const y = 40 + index * 40
    
    ctx.value.fillStyle = skill.active ? '#4CAF50' : '#666'
    ctx.value.font = '20px Arial'
    ctx.value.fillText(`${skill.icon} ${skill.name}`, x, y)
    
    // 渲染冷却条
    const cooldownPercent = Math.min(
      (Date.now() - skill.lastUsed) / skill.cooldown,
      1
    )
    ctx.value.fillStyle = '#ddd'
    ctx.value.fillRect(x + 100, y - 15, 40, 5)
    ctx.value.fillStyle = '#4CAF50'
    ctx.value.fillRect(x + 100, y - 15, 40 * cooldownPercent, 5)
  })
  
  // 渲染多人对战状态
  if (gameMode.value === 'battle') {
    players.value.forEach((player, index) => {
      ctx.value.fillStyle = '#000'
      ctx.value.font = '16px Arial'
      ctx.value.fillText(
        `${player.name}: ${player.score}`,
        10,
        60 + index * 25
      )
    })
  }
}

// 开始新游戏
const startNewGame = () => {
  score.value = 0
  gameOver.value = false
  foods.value = []
  
  // 初始化玩家
  if (gameMode.value === 'single') {
    initSnake()
  } else {
    players.value.forEach((player, index) => {
      player.snake = {
        body: [],
        direction: { x: index === 0 ? 1 : -1, y: 0 },
        speed: 5,
        color: skins[selectedSkin.value].colors[0],
        isInvincible: false
      }
      
      const startX = index === 0 
        ? Math.floor(GAME_WIDTH / (4 * GRID_SIZE))
        : Math.floor((GAME_WIDTH * 3) / (4 * GRID_SIZE))
      const startY = Math.floor(GAME_HEIGHT / (2 * GRID_SIZE))
      
      for (let i = 0; i < INITIAL_SNAKE_LENGTH; i++) {
        player.snake.body.push({
          x: startX + (index === 0 ? -i : i),
          y: startY
        })
      }
      
      player.score = 0
      player.alive = true
    })
  }
  
  generateFood()
  
  if (!isMuted.value) {
    sounds.background.loop = true
    sounds.background.play()
  }
}

// 组件挂载
onMounted(() => {
  // ... 保持之前的挂载逻辑 ...
  
  // 加载排行榜
  const savedLeaderboard = localStorage.getItem('snakeLeaderboard')
  if (savedLeaderboard) {
    leaderboard.value = JSON.parse(savedLeaderboard)
  }
})

// 组件卸载
onUnmounted(() => {
  // ... 保持之前的卸载逻辑 ...
  sounds.background.pause()
})
</script>

<template>
  <div class="snake-battle">
    <h1>贪吃蛇大作战</h1>
    
    <!-- 游戏设置 -->
    <div v-if="!gameLoop" class="game-settings">
      <input 
        v-model="playerName"
        placeholder="输入玩家名称"
        class="name-input"
      />
      
      <div class="mode-select">
        <button 
          v-for="mode in ['single', 'battle']"
          :key="mode"
          :class="{ active: gameMode === mode }"
          @click="gameMode = mode"
        >
          {{ mode === 'single' ? '单人模式' : '对战模式' }}
        </button>
      </div>
      
      <div class="difficulty-select">
        <button 
          v-for="diff in ['easy', 'normal', 'hard']"
          :key="diff"
          :class="{ active: difficulty === diff }"
          @click="difficulty = diff"
        >
          {{ {
            easy: '简单',
            normal: '普通',
            hard: '困难'
          }[diff] }}
        </button>
      </div>
      
      <div class="skin-select">
        <h3>选择皮肤</h3>
        <div class="skins">
          <div 
            v-for="(skin, id) in skins"
            :key="id"
            class="skin-option"
            :class="{ active: selectedSkin === id }"
            @click="selectedSkin = id"
          >
            <div 
              class="skin-preview"
              :style="{
                background: skin.pattern === 'gradient'
                  ? `linear-gradient(to right, ${skin.colors.join(',')})`
                  : skin.colors[0]
              }"
            ></div>
            <span>{{ skin.name }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 游戏画布 -->
    <div class="game-container">
      <canvas 
        ref="canvas"
        :width="GAME_WIDTH"
        :height="GAME_HEIGHT"
        class="game-canvas"
      ></canvas>
      
      <!-- 技能栏 -->
      <div class="skills-bar">
        <button 
          v-for="(skill, name) in skills"
          :key="name"
          class="skill-button"
          :class="{ active: skill.active }"
          :disabled="Date.now() - skill.lastUsed < skill.cooldown"
          @click="useSkill(name)"
        >
          {{ skill.icon }} {{ skill.name }}
        </button>
      </div>
      
      <!-- 控制按钮 -->
      <div class="controls">
        <button @click="startNewGame" :disabled="!gameOver">
          {{ gameOver ? '重新开始' : '游戏中' }}
        </button>
        <button @click="isMuted = !isMuted">
          {{ isMuted ? '🔇' : '🔊' }}
        </button>
      </div>
    </div>
    
    <!-- 排行榜 -->
    <div class="leaderboard">
      <h2>排行榜</h2>
      <div class="leaderboard-entries">
        <div 
          v-for="(entry, index) in leaderboard"
          :key="index"
          class="leaderboard-entry"
        >
          <span class="rank">{{ index + 1 }}</span>
          <span class="name">{{ entry.name }}</span>
          <span class="score">{{ entry.score }}</span>
          <span class="date">{{ entry.date }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* ... 保持之前的基础样式 ... */

.game-settings {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  align-items: center;
}

.name-input {
  padding: 8px;
  font-size: 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 200px;
}

.mode-select,
.difficulty-select {
  display: flex;
  gap: 10px;
}

.skin-select {
  text-align: center;
}

.skins {
  display: flex;
  gap: 15px;
  margin-top: 10px;
}

.skin-option {
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  transition: all 0.2s;
}

.skin-option.active {
  background: #e0e0e0;
}

.skin-preview {
  width: 40px;
  height: 20px;
  border-radius: 10px;
  margin-bottom: 5px;
}

.skills-bar {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.skill-button {
  padding: 8px 15px;
  font-size: 16px;
  background: #666;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.skill-button.active {
  background: #4CAF50;
}

.skill-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.leaderboard {
  margin-top: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
  max-width: 600px;
  width: 100%;
}

.leaderboard-entries {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.leaderboard-entry {
  display: grid;
  grid-template-columns: 50px 1fr 100px 100px;
  padding: 8px;
  background: #f5f5f5;
  border-radius: 4px;
}

.rank {
  font-weight: bold;
  color: #4CAF50;
}

.date {
  color: #666;
  font-size: 0.9em;
}

@media (max-width: 768px) {
  .game-canvas {
    width: 100%;
    height: auto;
  }
  
  .skills-bar {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .leaderboard-entry {
    font-size: 14px;
    grid-template-columns: 30px 1fr 70px 80px;
  }
}
</style> 